from django.conf import settings
from fdfs_client.client import Fdfs_client, os
from rest_framework import serializers

from goods.models import Brand

class BrandSerializer(serializers.ModelSerializer):

    class Meta:
        model = Brand
        fields = '__all__'

    def create(self, validated_data):
        # 生成连接fastdfs对象
        client = Fdfs_client(os.path.join(settings.BASE_DIR,'utils/fastdfs/client.conf'))
        # 获取图片数据
        image = validated_data['logo']
        # 以二进制数据上传
        res = client.upload_by_buffer(image.read())
        if res['Status'] !='Upload successed.':
            raise serializers.ValidationError('上传失败')
        # 保存链接
        image_path = res['Remote file_id']

        brand = Brand.objects.create(logo=image_path,name=validated_data['name'],first_letter=validated_data['first_letter'])

        brand.save()
        return brand

    def update(self, instance, validated_data):
        # 生成连接fastdfs对象
        client = Fdfs_client(os.path.join(settings.BASE_DIR, 'utils/fastdfs/client.conf'))
        # 获取图片数据
        image = validated_data['logo']
        # 以二进制数据上传
        res = client.upload_by_buffer(image.read())
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('上传失败')
        # 保存链接
        image_path = res['Remote file_id']
        brand = Brand.objects.all()
        brand.name=validated_data['name']
        brand.logo = image_path
        brand.first_letter = validated_data['first_letter']



        return brand

